package cn.yeamin.ms.service.impl;

import java.util.Arrays;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import cn.yeamin.ms.commons.Constats;
import cn.yeamin.ms.mapper.ResourceMapper;
import cn.yeamin.ms.mapper.RoleMapper;
import cn.yeamin.ms.service.support.BaseService;
import cn.yeamin.ms.utils.IsEmptyUtils;
import cn.yeamin.ms.vo.Resource;
import cn.yeamin.ms.vo.Role;

/**
 * @packageName: 包名: cn.yeamin.ms.service.impl
 * @classDesc: 类功能描述:(角色Service)
 * @author: Administrator
 * @createTime: 2017/7/28 10:12
 * @version: v1.0
 * @copyright:奕明(上海)影视传媒有限公司
 */
@Service
@Transactional
public class RoleService extends BaseService<Role> {

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private ResourceMapper resourceMapper;

	@Cacheable(value = Constats.ROLECACHENAME, key = "'findRoleByUserId_' + #uid")
	public Set<Role> findRoleByUserId(Long uid) {
		return roleMapper.findRoleByUserId(uid);
	}

	@CacheEvict(allEntries = true, cacheNames = { Constats.OTHERCACHENAME, Constats.RESOURCECACHENAME,
			Constats.ROLECACHENAME })
	public void grant(Long userId, Long roleId) {
		roleMapper.grant(userId, roleId);
	}

	@CacheEvict(allEntries = true, cacheNames = { Constats.OTHERCACHENAME, Constats.RESOURCECACHENAME,
			Constats.ROLECACHENAME })
	public void deleteGrant(Long userId, Long roleId) {
		roleMapper.deleteGrant(userId, roleId);
	}

	@CacheEvict(allEntries = true, cacheNames = { Constats.OTHERCACHENAME, Constats.RESOURCECACHENAME,
			Constats.ROLECACHENAME })
	public void grantResource(Long roleId, Long[] resourceIds) {
		if (resourceIds == null || "[]".equals(Arrays.toString(resourceIds))) {
			resourceMapper.deleteAll(roleId);
			return;
		}
		Role role = queryById(roleId);
		Assert.notNull(role, "角色不存在");
		Assert.state(!"administrator".equals(role.getRoleKey()), "超级管理员角色不能进行资源分配");
		Set<Resource> resources = resourceMapper.queryByIdForResources(roleId);
		if (!IsEmptyUtils.isEmptyForListOrSet(resources)) {
			for (Resource resource : resources) {
				resourceMapper.delResourceAndRole(roleId, resource.getId());
			}
		}
		for (Long rid : resourceIds) {
			resourceMapper.grant(roleId, rid);
		}

	}

	@CacheEvict(allEntries = true, cacheNames = { Constats.OTHERCACHENAME, Constats.RESOURCECACHENAME,
			Constats.ROLECACHENAME })
	public void deleteAll(Long id) {
		roleMapper.deleteAll(id);
	}

}
